package com.example.myapplication8.ui.sidebar

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

/**
 * 侧边栏ViewModel
 * 管理侧边栏的状态和数据
 */
class SidebarViewModel : ViewModel() {
    // 无障碍服务状态
    private val _accessibilityEnabled = MutableLiveData<Boolean>()
    val accessibilityEnabled: LiveData<Boolean> = _accessibilityEnabled

    // 悬浮窗权限状态
    private val _overlayPermissionGranted = MutableLiveData<Boolean>()
    val overlayPermissionGranted: LiveData<Boolean> = _overlayPermissionGranted

    // 前台服务状态
    private val _foregroundServiceRunning = MutableLiveData<Boolean>()
    val foregroundServiceRunning: LiveData<Boolean> = _foregroundServiceRunning

    // 应用版本信息
    private val _versionInfo = MutableLiveData<String>()
    val versionInfo: LiveData<String> = _versionInfo

    // 运行日志内容
    private val _logContent = MutableLiveData<String>()
    val logContent: LiveData<String> = _logContent

    private val _drawerState = MutableLiveData<Boolean>()
    val drawerState: LiveData<Boolean> = _drawerState

    private val _navigationEvent = MutableLiveData<Event<Int>>()
    val navigationEvent: LiveData<Event<Int>> = _navigationEvent

    private val _errorEvent = MutableLiveData<Event<String>>()
    val errorEvent: LiveData<Event<String>> = _errorEvent

    // 更新无障碍服务状态
    fun updateAccessibilityStatus(enabled: Boolean) {
        _accessibilityEnabled.value = enabled
    }

    // 更新悬浮窗权限状态
    fun updateOverlayPermission(granted: Boolean) {
        _overlayPermissionGranted.value = granted
    }

    // 更新前台服务状态
    fun updateForegroundService(running: Boolean) {
        _foregroundServiceRunning.value = running
    }

    // 更新版本信息
    fun updateVersionInfo(version: String) {
        _versionInfo.value = version
    }

    // 更新日志内容
    fun updateLogContent(log: String) {
        _logContent.value = log
    }

    fun setDrawerState(isOpen: Boolean) {
        try {
            _drawerState.value = isOpen
        } catch (e: Exception) {
            _errorEvent.value = Event("设置抽屉状态失败: ${e.message}")
        }
    }

    fun navigate(destinationId: Int) {
        try {
            _navigationEvent.value = Event(destinationId)
        } catch (e: Exception) {
            _errorEvent.value = Event("导航失败: ${e.message}")
        }
    }

    // 用于包装一次性事件
    class Event<out T>(private val content: T) {
        private var hasBeenHandled = false

        fun getContentIfNotHandled(): T? {
            return if (hasBeenHandled) {
                null
            } else {
                hasBeenHandled = true
                content
            }
        }

        fun peekContent(): T = content
    }
} 